﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Text;
using BP.OA;
namespace CCOA.App.NOTICE
{
    public partial class NoticeEdit : System.Web.UI.Page
    {
        #region //1.PI
        //权限控制
        private string FuncNo = null;
        private int rNoticeID
        {
            get
            {
                return Convert.ToInt32(Request.QueryString["OID"]);
            }
        }
        private DataTable GetAllEmps()
        {
            return BP.OA.GPM.GetAllEmps();
        }
        private DataTable GetAllDepts()
        {
            return BP.OA.GPM.GetAllDepts();
        }
        private DataTable GetAllStations()
        {
            return BP.OA.GPM.GetAllStations();
        }
        /// <summary>
        /// 当前用户No
        /// </summary>
        private string CurUserNo
        {
            get { return BP.Web.WebUser.No; }
        }
        /// <summary>
        /// 当前用户部门列表
        /// </summary>
        private DataTable CurUserDepts
        {
            get
            {
                if (BP.WF.Glo.OSModel == BP.Sys.OSModel.OneOne)
                {
                    return BP.DA.DBAccess.RunSQLReturnTable("SELECT * FROM Port_Dept WHERE No IN (SELECT FK_Dept FROM port_empdept WHERE FK_Emp='" + BP.Web.WebUser.No + "')");
                }
                return BP.OA.GPM.GetUserDeptsOfDatatable(BP.Web.WebUser.No);
            }
        }
        /// <summary>
        /// 获取通知类型
        /// </summary>
        /// <returns></returns>
        private DataTable GetAllNoticeCategory()
        {
            return BP.DA.DBAccess.RunSQLReturnTable("select No,Name from OA_NoticeCategory order by No");
        }
        private ListItem[] GetAllNoticeImportances()
        {
            return new ListItem[]
            {
                //new ListItem("未设置","0")
                //,new ListItem("不重要","1")
                //,
                new ListItem("<img src='/Images/Notice/Import0.png' style='width:15px;height:15px;'>普通","0")
                ,new ListItem("<img src='/Images/Notice/Import1.png' style='width:15px;height:15px;'>比较重要","1")
                ,new ListItem("<img src='/Images/Notice/Import2.png' style='width:15px;height:15px;'>很重要","2")
            };
        }
        private ListItem[] GetAllNoticeSta()
        {
            return new ListItem[]
            {
                new ListItem("自动","0")
                ,new ListItem("打开","1")
                ,new ListItem("关闭","2")
            };
        }
        private void BindListCtrl(object listData, object listCtrl, string textFormat, string defaultValue, string selectedValue)
        {
            if (listData is DataTable)
                BP.OA.UI.Dict.BindListCtrl((DataTable)listData, listCtrl, "Name", "No", textFormat, defaultValue, selectedValue);
            else if (listData is ListItem[])
                BP.OA.UI.Dict.BindListCtrl((ListItem[])listData, listCtrl, textFormat, defaultValue, selectedValue);
        }
        private int EditNotice(String Title, String Doc, String FK_NoticeCategory, String FK_Dept, int Importance
            , bool GetAdvices, String AdviceDesc, String AdviceItems, int NoticeSta, DateTime StartTime, DateTime StopTime
            , bool SendToPart, String SendToUsers, String SendToDepts, String SendToStations, String AttachFile, String[] Users)
        {
            BP.OA.Notice notice = new BP.OA.Notice(this.rNoticeID);
            notice.Title = Title;
            notice.Doc = Doc;
            notice.FK_NoticeCategory = FK_NoticeCategory.ToString();
            notice.RDT = DateTime.Now; ;
            notice.FK_Dept = FK_Dept;
            notice.FK_UserNo = BP.Web.WebUser.No;
            notice.Importance = Importance;
            notice.GetAdvices = GetAdvices;

            notice.SendToPart = SendToPart;
            notice.SendToDepts = SendToDepts;
            notice.SendToStations = SendToStations;
            notice.SendToUsers = SendToUsers;
            notice.AttachFile = AttachFile;
            //notice.SetMes = 0;
            if (GetAdvices)
            {
                notice.AdviceDesc = AdviceDesc;
                notice.AdviceItems = AdviceItems;
            }
            notice.NoticeSta = NoticeSta;
            if (NoticeSta == 0)
            {
                notice.StartTime = StartTime;
                notice.StopTime = StopTime;
            }
            int i = notice.Update();
            if (notice.OID == 0)
            {
                BP.OA.Debug.Alert(this, "修改失败！请联系管理员");
                return -1;
            }
            string str_users = String.Format(",{0},", String.Join(",", Users));
            string sql = String.Format("delete FROM OA_NoticeReader where FK_NoticeNo='{0}';", this.rNoticeID);
            BP.DA.DBAccess.RunSQL(sql);
            foreach (String user in Users)
            {
                sql = String.Format("Insert into OA_NoticeReader(FK_UserNo,FK_NoticeNo,myPK,AddTime) values('{0}',{1},'{2}',GetDate()); ", user, this.rNoticeID, Guid.NewGuid());
                BP.DA.DBAccess.RunSQL(sql);
            }
            return 1;
        }
        private void Alert(String msg)
        {
            BP.OA.Debug.Alert(this, msg);
        }
        private string GetUserNoList(int oid)
        {
            string sql = String.Format("Select FK_UserNo from OA_NoticeReader where FK_NoticeNo={0}", oid);
            System.Data.DataTable dt = BP.DA.DBAccess.RunSQLReturnTable(sql);
            List<String> l_users = new List<string>();
            foreach (DataRow dr in dt.Rows)
            {
                l_users.Add(String.Format("{0}", dr[0]));
            }
            return String.Join(",", l_users.ToArray());
        }
        private string GetUserNames(System.Data.DataTable dtEmps, string userNames)
        {
            List<String> l_users = new List<string>();
            foreach (DataRow dr in dtEmps.Rows)
            {
                if (String.Format(",{0},", userNames).Contains(String.Format(",{0},", Convert.ToString(dr["No"]))))
                    l_users.Add(String.Format("{0}", dr["Name"]));
            }
            return String.Join(",", l_users.ToArray());
        }
        private string GetDeptNames(System.Data.DataTable dtDepts, string depts)
        {
            List<String> l_depts = new List<string>();
            foreach (DataRow dr in dtDepts.Rows)
            {
                if (String.Format(",{0},", depts).Contains(String.Format(",{0},", Convert.ToString(dr["No"]))))
                    l_depts.Add(String.Format("{0}", dr["Name"]));
            }
            return String.Join(",", l_depts.ToArray());
        }
        private string GetStationNames(System.Data.DataTable dtStations, string stations)
        {
            List<String> l_stations = new List<string>();
            foreach (DataRow dr in dtStations.Rows)
            {
                if (String.Format(",{0},", stations).Contains(String.Format(",{0},", Convert.ToString(dr["No"]))))
                    l_stations.Add(String.Format("{0}", dr["Name"]));
            }
            return String.Join(",", l_stations.ToArray());
        }
        private void CloseWindow()
        {
            //string script = "<script language=JavaScript>for(var f in window.parent.frames)try{f.zDialog_close();break;}catch(err_x){;}</script>";
            //System.Web.UI.WebControls.Literal li = new System.Web.UI.WebControls.Literal();
            //li.Text = script;
            //page.Controls.Add(li);
        }
        /// <summary>
        /// 获取路径函数
        /// </summary>
        /// <returns></returns>
        private string GetAttachPathName()
        {
            string dir = String.Format("/DataUser/UploadFile/Notice/{0:yyyyMMdd}", DateTime.Now);
            return dir;
        }
        /// <summary>
        /// 获取新文件名函数
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        private string GetAttachFileName(string fileName)
        {
            string f = System.IO.Path.GetFileNameWithoutExtension(fileName);
            string ext = System.IO.Path.GetExtension(fileName);
            string newFileName = String.Format("{0}_{1:yyyyMMddHHmmss}{2}", f, DateTime.Now, ext);
            return newFileName;
        }
        /// <summary>
        /// 根据存储路径获取老文件名，必须是存储路径中包含老文件名才可。
        /// </summary>
        /// <param name="savePath"></param>
        /// <returns></returns>
        private string GetAttachOldFileName(string savePath)
        {
            String attachFile = System.IO.Path.GetFileName(savePath);
            String ext = System.IO.Path.GetExtension(savePath);
            //String[] arr_attachFile = attachFile.Split('_');
            //return String.Format("{0}{1}", arr_attachFile[0], ext);
            int index = attachFile.LastIndexOf('_');
            string oldName = attachFile.Substring(0, index);
            return String.Format("{0}{1}", oldName, ext);
        }
        public string GetAllAttachStr(string savePath, string splitter, string linkFormat)
        {
            if (splitter == null) splitter = ""; //"&nbsp;&nbsp;";
            if (String.IsNullOrEmpty(linkFormat)) linkFormat = "<a href='{1}'>{0}</a>";
            StringBuilder sb = new StringBuilder();
            String[] attachFiles = savePath.Split(new String[] { ";", ",", "|" }, StringSplitOptions.RemoveEmptyEntries);
            foreach (String attachFile in attachFiles)
            {
                if (sb.Length > 0) sb.Append(splitter);
                sb.AppendFormat(linkFormat
                    , this.GetAttachOldFileName(attachFile)
                    , attachFile);
            }
            return sb.ToString();
        }
        #endregion

        #region //2.Load
        protected void Page_Init(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                if (!BP.OA.GPM.IsCanUseFun(this.FuncNo)) { BP.OA.GPM.RedirectNoAccess(); return; }
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                this.LoadNoticeCategorys();
                this.LoadNoticeImportances();
                this.LoadNoticeNoticeSta();
                this.LoadDeptStruct();
                this.BindData();
            }
        }
        private void LoadNoticeCategorys()
        {
            this.BindListCtrl(this.GetAllNoticeCategory(), this.ui_FK_NoticeCategory, null, null, "04");
        }
        private void LoadDeptStruct()
        {
            this.BindListCtrl(this.CurUserDepts, ui_FK_Dept, null, null, null);
        }
        private void LoadNoticeImportances()
        {
            this.BindListCtrl(this.GetAllNoticeImportances(), this.ui_Importance, null, null, "0");
        }
        private void LoadNoticeNoticeSta()
        {
            this.BindListCtrl(this.GetAllNoticeSta(), this.ui_NoticeSta, null, null, "1");
        }
        private void BindData()
        {
            BP.OA.Notice notice = new BP.OA.Notice(this.rNoticeID);

            this.ui_Title.Text = notice.Title;
            this.ui_Doc.Text = notice.Doc;
            this.ui_FK_NoticeCategory.SelectedValue = notice.FK_NoticeCategory;

            if (!String.IsNullOrEmpty(notice.FK_Dept))
                this.div_Private.Style["display"] = "block";
            else
                this.div_Private.Style["display"] = "none";
            this.ui_FK_Dept.SelectedValue = notice.FK_Dept;

            this.ui_Importance.SelectedValue = notice.Importance.ToString();

            this.ui_GetAdvices.Checked = notice.GetAdvices;
            if (notice.GetAdvices)
                this.div_Advice.Style["display"] = "block";
            else
                this.div_Advice.Style["display"] = "none";
            this.ui_AdviceDesc.Text = notice.AdviceDesc;
            this.ui_AdviceItems.Text = notice.AdviceItems;

            this.ui_NoticeSta.SelectedValue = notice.NoticeSta.ToString();
            if (notice.NoticeSta == 0)
                this.div_AutoNoticeSta.Style["display"] = "block";
            else
                this.div_AutoNoticeSta.Style["display"] = "none";
            this.ui_StartTime.Text = notice.StartTime.ToString();
            this.ui_StopTime.Text = notice.StopTime.ToString();

            this.cb_Users.Checked = notice.SendToPart;
            if (!notice.SendToPart)
                this.div_Users.Style["display"] = "block";
            else
                this.div_Users.Style["display"] = "none";
            this.txt_UserNames.Value = notice.SendToUsers;
            this.txt_Users.Text = this.GetUserNames(this.GetAllEmps(), this.txt_UserNames.Value);
            this.txt_DeptNames.Value = notice.SendToDepts;
            this.txt_Depts.Text = this.GetDeptNames(this.GetAllDepts(), this.txt_DeptNames.Value);
            this.txt_StationNames.Value = notice.SendToStations;
            this.txt_Stations.Text = this.GetStationNames(this.GetAllStations(), this.txt_StationNames.Value);

            String attachPath = notice.AttachFile;
            //this.hlFile.Text=this.GetAttachOldFileName(attachPath);
            //this.hlFile.NavigateUrl=attachPath;
            this.hfAttachFiles.Value = attachPath;
            this.liAttachFiles.Text = this.GetAllAttachStr(attachPath, " ", "<div class='multi-old-div'><a href='#' class='multi-old-remove'>x</a>&nbsp;<a class='multi-old-url' href='{1}'>{0}</a></div>");
        }

        #endregion

        #region //3.Event
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            //1.获取UI变量
            String Title = this.ui_Title.Text;
            String Doc = this.ui_Doc.Text;
            String FK_NoticeCategory = this.ui_FK_NoticeCategory.SelectedValue;

            int Importance = Convert.ToInt32(this.ui_Importance.SelectedValue);

            String FK_Dept = null;
            if (!this.cb_Private.Checked) FK_Dept = this.ui_FK_Dept.SelectedValue;

            bool SendToPart = this.cb_Users.Checked;
            String SendToUsers = this.txt_UserNames.Value;
            String SendToDepts = this.txt_DeptNames.Value;
            String SendToStations = this.txt_StationNames.Value;

            bool GetAdvices = Convert.ToBoolean(this.ui_GetAdvices.Checked);
            String AdviceDesc = null;
            String AdviceItems = null;
            if (GetAdvices)
            {
                AdviceDesc = this.ui_AdviceDesc.Text;
                AdviceItems = this.ui_AdviceItems.Text;
            }

            int NoticeSta = Convert.ToInt32(this.ui_NoticeSta.SelectedValue);
            DateTime StartTime = System.DateTime.Now;
            DateTime StopTime = System.DateTime.Now;
            if (NoticeSta == 0)
            {
                StartTime = Convert.ToDateTime(this.ui_StartTime.Text);
                StopTime = Convert.ToDateTime(this.ui_StopTime.Text);
            }
            string[] users = null;
            if (!cb_Users.Checked)
            {
                //users = this.txt_UserNames.Value.Split(new String[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                DataTable dt = new DataTable();
                if (BP.WF.Glo.OSModel == BP.Sys.OSModel.OneMore)
                {
                    dt = BP.OA.GPM.GetFilteredEmps_BPM(SendToUsers, SendToDepts, SendToStations);
                }
                else
                {
                    dt = BP.OA.GPM.GetFilteredEmps(SendToUsers, SendToDepts, SendToStations);
                }

                String str_users = BP.OA.Main.GetValueListFromDataRowArray(dt.Select(), "{0}", ",", "No");
                users = str_users.Split(',');
            }
            else
            {
                List<String> ls = new List<string>();
                DataTable dt = BP.OA.GPM.GetAllEmps();
                foreach (DataRow dr in dt.Rows)
                {
                    if (!ls.Contains(Convert.ToString(dr["No"])))
                        ls.Add(Convert.ToString(dr["No"]));
                }
                users = ls.ToArray();
            }
            string AttachFile = this.hfAttachFiles.Value;
            //2.验证
            StringBuilder sbErrs = new StringBuilder();
            if (String.IsNullOrEmpty(Title))
            {
                sbErrs.Append("通知标题不能为空!");
            }
            if (String.IsNullOrEmpty(Doc))
            {
                sbErrs.Append(" 通知内容不能为空!");
            }
            if (users.Length == 0)
            {
                sbErrs.Append(" 请选择发送对象!");
            }
            if (sbErrs.Length != 0)
            {
                BP.OA.Debug.Alert(this, sbErrs.ToString());
                return;
            }

            //3.数据IO
            //3.1文件删除处理
            if (!String.IsNullOrEmpty(AttachFile))
            {
                StringBuilder sbOldFile = new StringBuilder();
                String[] oldFiles = AttachFile.Split(new String[] { ",", ";", "|" }, StringSplitOptions.RemoveEmptyEntries);
                foreach (String oldFile in oldFiles)
                {
                    if (oldFile.StartsWith("#"))
                    {
                        System.IO.File.Delete(Server.MapPath(oldFile.Substring(1)));
                    }
                    else
                    {
                        sbOldFile.AppendFormat("{0};", oldFile);
                    }
                }
                AttachFile = sbOldFile.ToString();
            }
            //3.2目录检测
            string dir = this.GetAttachPathName();
            if (!System.IO.Directory.Exists(Server.MapPath(dir)))
                System.IO.Directory.CreateDirectory(Server.MapPath(dir));
            HttpFileCollection hfc = Request.Files;
            for (int i = 0; i < hfc.Count; i++)
            {
                HttpPostedFile hpf = hfc[i];

                if (hpf.ContentLength > 0)
                {
                    string newFileName = this.GetAttachFileName(hpf.FileName);

                    string path = String.Format("{0}/{1}", dir, newFileName);
                    //string filePath = this.FileUpload1.PostedFile.FileName;
                    try
                    {
                        hpf.SaveAs(Server.MapPath(path));
                        AttachFile += String.Format("{0};", path);
                        //System.IO.File.Delete(Server.MapPath(hlFile.NavigateUrl));
                    }
                    catch
                    {
                        ;
                    }
                }
            }
            this.EditNotice(Title, Doc, FK_NoticeCategory, FK_Dept, Importance, GetAdvices, AdviceDesc, AdviceItems, NoticeSta, StartTime, StopTime, SendToPart, SendToUsers, SendToDepts, SendToStations, AttachFile, users);
            //4.统计与日志
            //this.Alert("");
            BP.OA.Debug.Confirm(this, "成功修改公告内容！返回公告管理？", "NoticeList.aspx", "");
            //this.CloseWindow();
            //this.Response.Redirect("NoticeList.aspx", true);
        }
        #endregion
    }
}